/* -*-jde-*- */
/* <Plot.java> */
package Practica2.plot;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Clase para poder llamar gnuplot
 *
 * @author Peralta Santa Anna Victor Miguel
 * @since November 2011
 */
public class Plot {

    /**
     * Ejecuta el comando plot de gnuplot para abrir el archivo fileName
     * @param fileName el nombre del archivo para graficar
     */
    public static void plot(final String fileName) {

        final File ruta = new File(".");
        Thread thread = new Thread() {

            @Override
            public void run() {
                try {
                    run("gnuplot " + ruta.getCanonicalPath() + "/" + fileName);
                } catch (IOException ex) {
                    Logger.getLogger(Plot.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        };

        thread.start();
    }

    /**
     * Toma un comando y la salida la pone en la terminal de bash.
     * @param comando 
     */
    private static void run(String comando) {
        try {

            String line;
            Process process;

            ProcessBuilder builder = new ProcessBuilder("/bin/bash");
            builder.redirectErrorStream(true);
            process = builder.start();

            OutputStream stdin = process.getOutputStream();
            InputStream stdout = process.getInputStream();

            BufferedReader reader = new BufferedReader(new InputStreamReader(stdout));
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stdin));


            String input = "";
            writer.write(input);
            writer.flush();

            input = comando;
            System.out.println("~$: " + input);


            writer.write("((" + input + ") && echo --EOF--) || echo --EOF--\n");

            writer.flush();


            line = reader.readLine();
            while (line != null && !line.trim().equals("--EOF--")) {

                System.out.println(": " + line);
                line = reader.readLine();
            }

            reader.close();
            writer.close();
            process.destroy();

        } catch (IOException ex) {
            Logger.getLogger(Plot.class.getName()).log(Level.SEVERE, null, ex);
            System.err.println(ex.getMessage());
            System.err.println("Error en la ejecución del comando bash");
        }
    }

    /**
     * Ejecutamos el comando ejemplo.
     * @param args 
     */
    public static void main(String args[]) {

        Plot.plot("plot.txt");
    }
}
